package com.lening.common.handler;

import com.lening.common.annotation.ResponseNotResult;
import com.lening.common.web.Result;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.List;



@Getter
@Setter
@ControllerAdvice
@ConfigurationProperties(prefix = "response")
public class ResponseResultHandler implements ResponseBodyAdvice<Object> {

    private List<String> success;

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        ResponseNotResult annotation = returnType.getMethodAnnotation(ResponseNotResult.class);
        if(annotation != null){
            return body;
        }

        if (returnType.getParameterType() == Result.class) {
            return body;
        }

        if (returnType.getParameterType() == String.class && StringUtils.hasText(body.toString()) && success.stream().noneMatch(item -> body.toString().contains(item))) {
            return Result.fail(body.toString());
        } else {
            return Result.ok(body);
        }
    }
}
